//获取应用实例
import * as util from '../../../utils/UmfUtils.js';
import pickerview from '../../../common/view/pickerview/pickerView';
import location from '../../../common/code/pickerList/location';
import hyTypes from '../../../common/code/pickerList/hyType.js'
import * as bank from '../../../common/code/pickerList/bank.js';
import alipayList from '../../../common/code/pickerList/alipay';
import wechatList from '../../../common/code/pickerList/wechat';
import * as profitType from '../../../common/code/pickerList/profitType';
import constants from '../../../common/Constants';
import network_utils from '../../../http/NetworkUtils';
import * as cacheUtils from '../../../model/CacheUtils';
import PickerUtils from '../../../model/PickerUtils';
import * as umfDialog from '../../../utils/UmfDialog.js';
import TimeUtils from "../../../utils/TimeUtils";
import UmfLog from '../../../utils/UmfLog';

const app = getApp();

let InfoSubmitParams = {};
let photoInfo = null;
let flagArray = [];
let posPhotoCSData = null;
let step_no_info = constants.PosInfoSteps.STEP_NO_INFO;
let step_no_complete = constants.PosInfoSteps.STEP_NO_COMPLETE;
let step_complete = constants.PosInfoSteps.STEP_COMPLETE;
let step_no_submit = constants.PosInfoSteps.STEP_NO_SUBMIT;
let step_submit = constants.PosInfoSteps.STEP_SUBMITED;
Page({
  data: {
    listArr: [{ name: "基本信息", flag: 0, bindEvent: "gotoBasisInfo" },
    { name: "终端信息", flag: 0, bindEvent: "gotoTerminal" },
    { name: "费率码牌信息", flag: 0, bindEvent: "gotoFeeRate" },
    { name: "补充上传图片", flag: 3, bindEvent: "gotoUploadPhoto" },
    ],
    
  },

  onLoad: function (options) {
    this.setData({
      storeId: options.storeId,
      posFrom: options. posFrom,
      isQuery: options.isQuery,
      isStore: options.isStore,
      basisInfo: options.basisInfo ? JSON.parse(basisInfo):{},
      storeAddress:options.storeAddress,
      merIdBb:options.merIdBb
    })
    // if(options.posFrom=="selfDeploy"){
    //   this._requestPosInfo()
    // }
    setListTittle(this,options.posFrom)   
  },


  onShow: function (e) {
    
    let basisManager = new cacheUtils.cacheManager().init("basisInfo" + this.data.storeId, constants.STORAGE_FUNC.BASIS_INFO);
    flagArray = basisManager.getFunc();
    let pageListArray = this.data.listArr;

    photoInfo = new cacheUtils.cacheManager()
      .init("uploadPOSphoto" + this.data.storeId, constants.STORAGE_FUNC.POSPHOTO);
    posPhotoCSData = photoInfo.getFunc();
    if (posPhotoCSData) {
      this.setData({
        photoInfoData: posPhotoCSData.photoInfoData
      })
      pageListArray[3].flag = stateUtil(posPhotoCSData.flag ? posPhotoCSData.flag : step_no_submit.code);
    }else{
      pageListArray[3].flag =  stateUtil(step_no_submit.code)
    }
    pageListArray[0].flag = stateUtil(flagArray && flagArray["basisPOSInfo"] ? flagArray["basisPOSInfo"] : step_no_info.code);  
    pageListArray[1].flag = stateUtil(flagArray && flagArray["terminalPOSInfo"] ? flagArray["terminalPOSInfo"] : step_no_info.code);
    pageListArray[2].flag = stateUtil(flagArray && flagArray["feeRateInfo"] ? flagArray["feeRateInfo"] : step_no_info.code);
    
    this.setData({
      listArr: pageListArray,
    });
  },

  gotoBasisInfo: function () {
    //测试
    // this.setData({
    //   basisInfoData: JSON.stringify({
    //     preState:'0',
    //     contrId:'11122111',
    //     hyType:'其他',
    //     starttime:'18:00',
    //     endtime:'22:09'
    //   })
    // })
    wx.navigateTo({
      url: 'basisPosInfo/basisPosInfo?storeId=' + this.data.storeId+'&basisInfoData='+this.data.basisInfoData,
    })
  },
  gotoTerminal: function () {
    wx.navigateTo({
      url: 'terminalPosInfo/terminalPosInfo?storeId=' + this.data.storeId+'&terminalInfoData='+this.data.terminalInfoData,
    })
  },
  gotoFeeRate:function(){
    wx.navigateTo({
      url: 'feeRateInfo/feeRateInfo?storeId=' + this.data.storeId + '&posFrom=' + this.data.posFrom + '&feeRateInfoData=' + this.data.feeRateInfoData,
    })
  },
  
  gotoUploadPhoto: function () {
    if (this.data.posPhotoInfoData){
      wx.navigateTo({
        url: 'uploadPosPhoto/uploadPosPhoto?storeId=' + this.data.storeId + '&posPhotoInfoData=' + this.data.posPhotoInfoData,
      })
      return
    }
      let params = {
        storeId: this.data.storeId
      };
      network_utils.buildRequest(constants.Interfaces.FUNC_MERCHANT_DETAIL, params, {
        doHttpSucess: (response) => {
          if (constants.RetCodes.SUCCESS === response.retCode) {
            let {
              payeeCardPhotoFrontUrl, payeeCardPhotoConUrl, categoryCardPhotoFrontUrl,
              categoryCardPhotoCon, shopSignFrontUrl, shopInUrl, storeLicenseNoUrl,
              authCertUrl
            } = response;
            let photoInfoData = [];
            let thisPhontInfo = [];
            //TODO  将企业入网的照片加入
            payeeCardPhotoFrontUrl && photoInfoData.push(encodeURIComponent(payeeCardPhotoFrontUrl)) && thisPhontInfo.push(payeeCardPhotoFrontUrl);
            payeeCardPhotoConUrl && photoInfoData.push(encodeURIComponent(payeeCardPhotoConUrl)) && thisPhontInfo.push(payeeCardPhotoConUrl);

            categoryCardPhotoFrontUrl && photoInfoData.push(encodeURIComponent(categoryCardPhotoFrontUrl)) && thisPhontInfo.push(categoryCardPhotoFrontUrl);
            categoryCardPhotoCon && photoInfoData.push(encodeURIComponent(categoryCardPhotoCon)) && thisPhontInfo.push(categoryCardPhotoCon);
            authCertUrl && photoInfoData.push(encodeURIComponent(authCertUrl)) && thisPhontInfo.push(authCertUrl);

            shopSignFrontUrl && photoInfoData.push(encodeURIComponent(shopSignFrontUrl)) && thisPhontInfo.push(shopSignFrontUrl);
            shopInUrl && photoInfoData.push(encodeURIComponent(shopInUrl)) && thisPhontInfo.push(shopInUrl);
            storeLicenseNoUrl && photoInfoData.push(encodeURIComponent(storeLicenseNoUrl)) && thisPhontInfo.push(storeLicenseNoUrl);
            this.setData({
              photoInfoData: thisPhontInfo
            })
            photoInfo.cacheFunc({ photoInfoData: thisPhontInfo })
            wx.navigateTo({
              url: 'uploadPosPhoto/uploadPosPhoto?storeId=' + this.data.storeId + '&photoInfoData=' + JSON.stringify(photoInfoData),
            })
            return true;
          }
          return false;
        }
      }).send();
      return true;    

  },

  nextStep: function (e) {
    
    let formId = e.detail.formId
    InfoSubmitParams = {};
    let msg = "请将所有信息填写完成，再进行提交！";
    if (flagArray) {
      if (flagArray["basisPOSInfo"] != step_complete.code || flagArray["feeRateInfo"] != step_complete.code || flagArray["terminalPOSInfo"] != step_complete.code || posPhotoCSData.flag != step_submit.code) {
        umfDialog.show(msg)
        return;
      } else {
        InfoSubmitParams["formId"]= formId    //推送用 
        InfoSubmitParams["posFrom"] = this.data.posFrom 
        InfoSubmitParams["installAddr"] = PickerUtils.getLinkedHZByCode(location, this.data.storeAddress).join("-")
        InfoSubmitParams["formId"] = e.detail.formId;
        //基本信息
        let basiscacheManager = new cacheUtils.cacheManager()
          .init("basisPOSInfo" + this.data.storeId, constants.STORAGE_FUNC.POS_BAS_INFO);
        let posBasisCSData = basiscacheManager.getFunc();
        this._setBasisPosParams(posBasisCSData);

        //费率信息
        let feeRateManager = new cacheUtils.cacheManager()
          .init("feeRateInfo" + this.data.storeId, constants.STORAGE_FUNC.FEERATE_INFO);
        let feeRateInfo = feeRateManager.getFunc();
        this._setFeeRateParams(feeRateInfo);

        //终端信息
        let terminalManager = new cacheUtils.cacheManager()
          .init("terminalPOSInfo" + this.data.storeId, constants.STORAGE_FUNC.TERMINALPOSINFO);
        let terminalInfo = terminalManager.getFunc();
        this._setTerminalPOSParams(terminalInfo);
        //照片信息
        // let photoInfoData = this.data.photoInfoData
        // photoInfoData.push(posPhotoCSData.busiAgreement[0].imgRemoteUrl)
        // photoInfoData.push(posPhotoCSData.busiAgreement[1].imgRemoteUrl)
        // for (let i = 0; i < posPhotoCSData.successUp ? posPhotoCSData.successUp.length:0; i++) {
        //   photoInfoData.push(posPhotoCSData.successUp[i].imgRemoteUrl);
        // }
        // InfoSubmitParams["imgUrl"] = JSON.stringify(photoInfoData);
        //网络请求
        // InfoSubmitParams["callbackUrl"] = "http\://10.10.56.145\:8180/merchantProductDeploy/posCallbackMethod";
         InfoSubmitParams["callbackUrl"] = constants.url() + constants.Interfaces.FUNC_POS_CB;
        InfoSubmitParams["storeId"] = this.data.storeId;
        InfoSubmitParams["agentType"] = constants.AGENT_TYPE;
        this._requestOpenPOS();
      }
    } else {
      umfDialog.show(msg, this, false)
    }
  },
  //基本信息数据处理
  _setBasisPosParams: function (data) {
    let hyType = PickerUtils.getNormalCodeByHZ(hyTypes, data["hyType"]).toString();
    InfoSubmitParams["hyType"] = hyType?hyType:"14" ;//行业类别
    
    InfoSubmitParams["preState"] = data["preState"] ? "0" : "1";//申请开通预授权
    InfoSubmitParams["starttime"] = data["starttime"] ? data["starttime"] : "09:00";//营业开始时间
    InfoSubmitParams["endtime"] = data["endtime"] ? data["endtime"] : "21:00";//营业结束时间
    InfoSubmitParams["contrId"] = data["contrId"];
    if (data["remark"]) {
      InfoSubmitParams["remark"] = data["remark"];
    }
    UmfLog.log("基本信息");
    UmfLog.log(InfoSubmitParams);

  },

  
  //终端信息
  _setTerminalPOSParams: function (data) {
    
    InfoSubmitParams["installAreaInf"]=data["installArea"]
    InfoSubmitParams["getTermAmt"] = util.yuanToFen(data["getTermAmt"]).toString();

    InfoSubmitParams["modelNames"] = [];
    InfoSubmitParams["terminalNums"] = [];
    
    InfoSubmitParams["snNumber"]=[];  //终端序列号
    let terminalItemArray = convertEmptyModel(data["terminalItem"]);
    for (let index in terminalItemArray) {
      let snNumberArr = []
      InfoSubmitParams["modelNames"].push(terminalItemArray[index]["modelNames"]);
      InfoSubmitParams["terminalNums"].push(terminalItemArray[index]["terminalNums"]);
      for (let i = 0; i < terminalItemArray[index].serialArr.length;i++){
        snNumberArr.push(terminalItemArray[index]["serialArr"][i]["value"])
      }      
      InfoSubmitParams["snNumber"].push(snNumberArr.join(','))
    }
    InfoSubmitParams["modelNames"] = InfoSubmitParams["modelNames"].join("-");
    InfoSubmitParams["terminalNums"] = InfoSubmitParams["terminalNums"].join("-");
    InfoSubmitParams["snNumber"] = InfoSubmitParams["snNumber"].join("-")
    UmfLog.log("终端");
    UmfLog.log(InfoSubmitParams);
  },
  //费率码牌信息
  _setFeeRateParams:function(data){
    //费率*100
    InfoSubmitParams["jfeerate"] = util.yuanToFen(data["jfeerate"]).toFixed(2).toString();
    InfoSubmitParams["dfeerate"] = util.yuanToFen(data["dfeerate"]).toFixed(2).toString();
    InfoSubmitParams["debitCapamt"] = util.yuanToFen(data["debitCapamt"]).toString();
    //支付宝费率 微信费率  收款码
    InfoSubmitParams["wechatRate"] = data["wxrate"]
    InfoSubmitParams["alipayRate"] = data["alirate"] 
    InfoSubmitParams["qrCodeList"] = data["qrCodeListSubmit"]
  },

  _requestOpenPOS: function () {
    let params = InfoSubmitParams;
    network_utils.buildRequest(constants.Interfaces.FUNC_OPENPOS_SUBMIT, params, {
      doHttpSucess: (response) => {
        if (constants.RetCodes.SUCCESS === response.retCode) {
          this._requestSuccess(response);
          
          return true;
        }
        return false;
      }
    }).send();
  },
  _requestSuccess: function (result) {
    //清除缓存
    _clearCache("basisInfo" + this.data.storeId, constants.STORAGE_FUNC.BASIS_INFO);
    _clearCache("basisPOSInfo" + this.data.storeId, constants.STORAGE_FUNC.POS_BAS_INFO);
    _clearCache("feeRateInfo" + this.data.storeId, constants.STORAGE_FUNC.FEERATE_INFO);
    _clearCache("terminalPOSInfo" + this.data.storeId, constants.STORAGE_FUNC.TERMINALPOSINFO);
    photoInfo.clearFunc();
    if (this.data.posFrom=='basis'){
      let jsonData = {
        storeId: result["storeId"] ? result["storeId"] : "",
        storeShortName: result["storeShortName"] ? result["storeShortName"] : "",
        payeeName: result["payeeName"] ? result["payeeName"] : "",
        qrUrl: result["qrCodeUrl"] ? encodeURIComponent(result["qrCodeUrl"]) : ""
      };
      wx.redirectTo({
        url: '../inviteMerchants/inviteMerchants?jsonData=' + JSON.stringify(jsonData),
      });
    }
    else if (this.data.posFrom == 'detail'){
      //补开  跳到自助部署列表
      wx.switchTab({
        url: '/pages/selfhelpDeployment/selfhelpDeployment'
      })
    }
    
  },
  _requestPosInfo(){
    let params={
      storeId:this.data.storeId,
      merIdBb: this.data.merIdBb
    }
    let that = this
    network_utils.buildRequest(constants.Interfaces.FUNC_POS_QUERYINFO, params, {
      doHttpSucess: (response) => {
        if (constants.RetCodes.SUCCESS === response.retCode) {
          _querySuccess(this,response);
          return true;
        }
        return false;
      }
    }).send();
    
  }
});

function stateUtil(flag) {
  //根据状态返回标志
  if (flag == step_no_info.code) {
    return step_no_info.name;
  } else if (flag == step_no_complete.code) {
    return step_no_complete.name;
  } else if (flag == step_complete.code) {
    return step_complete.name;
  } else if (flag == step_no_submit.code) {
    return step_no_submit.name;
  } else if (flag == step_submit.code) {
    return step_submit.name;
  } else if (flag == "") {
    return ""
  }
}

function _clearCache(key, func) {
  let cacheManager = new cacheUtils.cacheManager()
    .init(key, func);
  cacheManager.clearFunc(key, func);
}

function isEmptyOrNull(data) {
  for (var obj in data) {
    if (data[obj].length > 0) {
      return false;
    }
  }
  return true;
}

function getKeyWithObjc(data) {
  let array = [];
  for (var obj in data) {
    array.push(obj);
  }
  return array;
}


/**
 * 提取机具模型里不为空的数据
 */
function convertEmptyModel(modelArray) {
  let helpers = {
    filterModel: (item) => {
      return item["modelNames"] && item["terminalNums"];
    },
  };
  return modelArray.filter(helpers.filterModel);
}

function setListTittle(page,posFrom){
  if (posFrom == 'basis' || posFrom == 'detail') {
    page.setData({
      listTittle: "补充信息"
    })
  } else if (posFrom == 'selfDeploy'&&page.data.isRevise=='true'){
    page.setData({
      listTittle: "信息修改"
    })
  }
}

//从自助部署跳转过来请求POS信息成功
function _querySuccess(page,data){
  let disabled = { disabled: page.data.isQuery === "true"} 
  if(!disabled){
    //如果是待修改，将每个页面的flag都设为已填完或已提交
  }
  let basisInfoData = disabled, feeRateInfoData = disabled, terminalInfoData = disabled,posPhotoInfoData=disabled
  //基本信息
  basisInfoData["hyType"] = PickerUtils.getNormalHZByCode(hyTypes, data["hyType"]).toString()
  basisInfoData["preState"] = data["preState"]//申请开通预授权
  basisInfoData["starttime"] = data["starttime"]
  basisInfoData["endtime"] = data["endtime"]//营业结束时间
  basisInfoData["contrId"] = data["contrId"]
  basisInfoData["remark"] = data["remark"];
  //终端信息
  terminalInfoData["installArea"] = data["installAreaInf"]
  terminalInfoData["getTermAmt"] = util.fentoyuan(data["getTermAmt"]).toString();
  terminalInfoData["modelNames"] = data["modelNames"];
  terminalInfoData["terminalNums"] = data["terminalNums"];
  terminalInfoData["snNumber"] = data["snNumber"];  //终端序列号
  //费率信息
  feeRateInfoData["jfeerate"] = util.fentoyuan(data["jfeerate"]).toString();
  feeRateInfoData["dfeerate"] = util.fentoyuan(data["dfeerate"]).toString();
  feeRateInfoData["debitCapamt"] = util.fentoyuan(data["debitCapamt"]).toString();
  //支付宝费率 微信费率  收款码
  feeRateInfoData["wechatRate"] = data["wxrate"]
  feeRateInfoData["alipayRate"] = data["alirate"]
  feeRateInfoData["qrCodeList"] = data["qrCodeList"]
  //图片URL
  // posPhotoInfoData["imgUrl"] = data["imgUrl"]  //后面json.parse处理TODO

  page.setData({
    basisInfoData: JSON.stringify(basisInfoData) ,
    feeRateInfoData: JSON.stringify(feeRateInfoData),
    terminalInfoData: JSON.stringify(terminalInfoData),
    posPhotoInfoData: posPhotoInfoData,
    listArr: [{ name: "基本信息", flag: 2, bindEvent: "gotoBasisInfo" },
      { name: "终端信息", flag: 2, bindEvent: "gotoTerminal" },
      { name: "费率码牌信息", flag: 2, bindEvent: "gotoFeeRate" },
      { name: "补充上传图片", flag: 4, bindEvent: "gotoUploadPhoto" },
      ],
  })
}




